import axios from 'axios'
import router from '@/router/index'
import { useUserOutsideStore } from '@/store/modules/user'

const toLogin = () => {
	const userOutsideStore = useUserOutsideStore()
	userOutsideStore.logout().then(() => {
		router.push({
			name: 'login',
			query: {
				redirect: router.currentRoute.value.path !== '/login' ? router.currentRoute.value.fullPath : undefined
			}
		})
	})
}

const api = axios.create({
	baseURL: import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === 'true' ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
	timeout: 20000,
	responseType: 'json'
})

api.interceptors.request.use((request) => {
	const userOutsideStore = useUserOutsideStore()
	/**
	 * 全局拦截请求发送前提交的参数
	 * 以下代码为示例，在请求头里带上 token 信息
	 */
	if (userOutsideStore.isLogin) {
		// request.headers["Token"] = userOutsideStore.token;
		// 是否将 POST 请求参数进行字符串化处理
		// if (request.method === "post") {
		request.data.UserToken = userOutsideStore.token
		request.data.SessionId = userOutsideStore.xssessionid
		request.data.Sign = ''
		request.data.Key = ''
		// }
	} else {
		request.data.UserToken = ''
		request.data.SessionId = ''
		request.data.Sign = ''
		request.data.Key = ''
	}

	return request
})

api.interceptors.response.use(
	(response) => {
		if (response.data.Code === 1000) {
			if (typeof response.data.Data == 'string') {
				try {
					response.data.Data = JSON.parse(response.data.Data)
				} catch (e) {}
			}
			return Promise.resolve(response.data)
		} else if ([2000, 3000].includes(response.data.Code)) {
			return Promise.resolve(response.data)
		} else if (response.data.Code === 9999) {
			toLogin()
		} else {
		}
	},
	(error) => {
		let message = error.message
		if (message == 'Network Error') {
			message = '后端网络故障'
		} else if (message.includes('timeout')) {
			message = '接口请求超时'
		} else if (message.includes('Request failed with status code')) {
			message = '接口' + message.substr(message.length - 3) + '异常'
		}
		ElMessage({
			message,
			type: 'error'
		})
		return Promise.reject(error)
	}
)

export default api
